package yangsw87.service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import yangsw87.interfaces.CdinfoService;
import yangsw87.model.CdInfoVO;

public class JDBCCdinfo implements CdinfoService{
	
	private static final String DRV = "oracle.jdbc.OracleDriver";
	private static final String URL = "jdbc:oracle:thin:@//localhost:1521/xe";
	private static final String USR = "scott";
	private static final String PWD = "TIGER";

//	private static final String createSQL = " create table cdinfo(cd_id char(5) primary key, "+
//			" title VARCHAR(50) not NULL, " +
//			" publisher VARCHAR(30) not null, " +
//			" artist VARCHAR(20) not null, "+
//			" price number(10) default 0) ";
	private static final String insertSQL = " insert into cdinfo(cd_id, title, publisher, artist, price) "
			+ " VALUES(?,?,?,?,?)";
	private static final String selectSQL = " select * from cdinfo order by cd_id desc ";
	
	@Override
	public boolean newCDinfo(CdInfoVO cd) {
		
		Connection conn = null;
		PreparedStatement ps = null;
		boolean result = false;
		
		try {
			Class.forName(DRV);
			conn = DriverManager.getConnection(URL, USR, PWD);
			ps = conn.prepareStatement(insertSQL);
			// ? 매개변수에 들어갈 실제 값을 지정
			ps.setString(1, cd.getCd_id()); 
			ps.setString(2, cd.getTitle()); 
			ps.setString(3, cd.getPublisher()); 
			ps.setString(4, cd.getArtist());
			ps.setInt(5, cd.getPrice());

			int cnt = ps.executeUpdate();
			// 성공적으로 insert 되면 result를 true로
			if (cnt > 0)
				result = true;

		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			if (ps != null)
				try {
					ps.close();
				} catch (Exception e) {
				}
			if (conn != null)
				try {
					conn.close();
				} catch (Exception e) {
				}
		}
		return result;
		
	}

	@Override
	public String readCDinfo() {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String result = "";

		try {
			Class.forName(DRV);
			conn = DriverManager.getConnection(URL, USR, PWD);
			ps = conn.prepareStatement(selectSQL);
			rs = ps.executeQuery();

			// selectSQL 실행결과를 모두 출력
			while (rs.next()) {
				for (int i = 1; i <= 9; ++i) {
					result += rs.getString(i) + "  ";
				}
				result += "\n";
			}

		} catch (Exception e) {
		} finally { // 위에 try안에 들어있는 변수의 순서의 역순으로 닫아야 하기때문에 순서가 중요함!
			if (rs != null)
				try {
					rs.close();
				} catch (Exception e) {
				}
			if (ps != null)
				try {
					ps.close();
				} catch (Exception e) {
				}
			if (conn != null)
				try {
					conn.close();
				} catch (Exception e) {
				}
		}
		return result;
	}

	
	

}
